<!DOCTYPE html>
<!--
  The MIT License (MIT)

  Copyright (c) 2017 Tarek Sherif

  Permission is hereby granted, free of charge, to any person obtaining a copy of
  this software and associated documentation files (the "Software"), to deal in
  the Software without restriction, including without limitation the rights to
  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  the Software, and to permit persons to whom the Software is furnished to do so,
  subject to the following conditions:

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<html>
<head>
    <title>PicoGL.js: Render to Cubemap</title>
    <meta charset="utf-8">
    <script src="utils/gl-matrix.js"></script>
    <script src="../build/picogl.js"></script>
    <script src="utils/utils.js"></script>
    <link rel="stylesheet" href="../site/css/picogl-example.css"> 
</head>
<body>
    <div id="example-title">
        PicoGL.js Example: Render to Cubemap
        <div>
            <a href="https://github.com/tsherif/picogl.js/blob/master/examples/render-to-cubemap.html">Source code</a>
        </div>
    </div>
    <canvas id="gl-canvas"></canvas>
    <script type="x-shader/vs" id="vertex-skybox">
        #version 300 es
        
        layout(std140, column_major) uniform;

        layout(location=0) in vec4 position;
        layout(location=1) in vec2 uv;
        
        uniform SceneUniforms {
            mat4 uViewProj;
            vec4 uEyePosition;
        };
        
        out vec3 vPosition;
        out vec2 vUV;
        void main() {
            vec4 worldPosition = vec4(position.xyz * 5.0, 1.0);            
            vPosition = position.xyz;
            vUV  = uv;
            gl_Position = uViewProj * worldPosition;
        }
    </script>
    <script type="x-shader/vf" id="fragment-skybox">
        #version 300 es
        precision highp float;
        
        layout(std140, column_major) uniform;

        
        uniform SceneUniforms {
            mat4 uViewProj;
            vec4 uEyePosition;
        };

        uniform samplerCube renderCubemap;
        uniform samplerCube skyCubemap;
        
        in vec3 vPosition;
        in vec2 vUV;

        out vec4 fragColor;
        void main() {
            vec3 debugColor;
            vec3 mags = abs(vPosition);
            if (mags.x > mags.y && mags.x > mags.z) {
                debugColor = vPosition.x > 0.0 ? vec3(0.2, 0.0, 0.0) : vec3(0.0, 0.2, 0.0); 
            } else if (mags.y > mags.x && mags.y > mags.z) { 
                debugColor = vPosition.y > 0.0 ? vec3(0.0, 0.0, 0.2) : vec3(0.2, 0.2, 0.0); 
            } else {
                debugColor = vPosition.z > 0.0 ? vec3(0.0, 0.2, 0.2) : vec3(0.2, 0.0, 0.2); 
            }
            vec3 color = texture(renderCubemap, vPosition).rgb * texture(skyCubemap, vPosition).rgb;
            fragColor = vec4(color, 1.0);
        }
    </script>
    <script type="x-shader/vs" id="vertex-cube">
        #version 300 es
        
        layout(std140, column_major) uniform;

        layout(location=0) in vec4 position;
        layout(location=1) in vec2 uv;
        layout(location=2) in vec4 normal;
        
        uniform SceneUniforms {
            mat4 uViewProj;
            vec4 uEyePosition;
        };

        uniform mat4 uModel;
        
        out vec3 vPosition;
        out vec2 vUV;
        out vec3 vNormal;

        out vec3 vModelPosition;

        void main() {
            vModelPosition = position.xyz;
            vec4 worldPosition = uModel * position;
            vPosition = worldPosition.xyz;
            vUV = uv;
            vNormal = (uModel * normal).xyz;
            gl_Position = uViewProj * worldPosition;
        }
    </script>
    <script type="x-shader/vf" id="fragment-cubemap">
        #version 300 es
        precision highp float;

        layout(std140, column_major) uniform;
        
        uniform SceneUniforms {
            mat4 uViewProj;
            vec4 uEyePosition;
        };

        uniform sampler2D tex;
        
        in vec2 vUV;

        layout(location=0) out vec4 fragColor;
        layout(location=1) out vec4 fragColor1;
        layout(location=2) out vec4 fragColor2;
        layout(location=3) out vec4 fragColor3;
        layout(location=4) out vec4 fragColor4;
        layout(location=5) out vec4 fragColor5;

        void main() {
            fragColor = vec4(texture(tex, vUV).rgb, 1.0);
            fragColor1 = fragColor;
            fragColor2 = fragColor;
            fragColor3 = fragColor;
            fragColor4 = fragColor;
            fragColor5 = fragColor;
        }
    </script>
    <script type="x-shader/vf" id="fragment-cube">
        #version 300 es
        precision highp float;

        layout(std140, column_major) uniform;
        
        uniform SceneUniforms {
            mat4 uViewProj;
            vec4 uEyePosition;
        };

        uniform samplerCube renderCubemap;
        uniform samplerCube skyCubemap;
        
        in vec3 vPosition;
        in vec3 vNormal;

        in vec3 vModelPosition;

        out vec4 fragColor;

        void main() {
            vec3 normal = normalize(vNormal);
            vec3 viewVec = normalize(vPosition - uEyePosition.xyz);
            vec3 dir = reflect(viewVec, normal);
            vec3 color1 = texture(renderCubemap, dir).rgb;
            vec3 color2 = texture(skyCubemap, dir).rgb;
            fragColor = vec4(color1 * color2, 1.0);
        }
    </script>
    <script type="text/javascript">
        utils.addTimerElement();
        utils.timerDiv.style.color = "black";
        
        var canvas = document.getElementById("gl-canvas");

        if (!utils.testWebGL2()) {
            console.error("WebGL 2 not available");
            document.body.innerHTML = "This example requires WebGL 2 which is unavailable on this system."
        }

        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var CUBEMAP_DIM = 2048;
        
        var app = PicoGL.createApp(canvas)
        .clearColor(1.0, 1.0, 1.0, 1.0)
        .depthTest();

        var timer = app.createTimer();

        // FRAMEBUFFER
        var colorTarget = app.createCubemap({
            width: CUBEMAP_DIM,
            height: CUBEMAP_DIM
        });
        var depthTarget = app.createRenderbuffer(CUBEMAP_DIM, CUBEMAP_DIM, PicoGL.DEPTH_COMPONENT16);

        var cubemapBuffer = app.createFramebuffer()
        .colorTarget(0, colorTarget, PicoGL.TEXTURE_CUBE_MAP_NEGATIVE_X)
        .colorTarget(1, colorTarget, PicoGL.TEXTURE_CUBE_MAP_POSITIVE_X)
        .colorTarget(2, colorTarget, PicoGL.TEXTURE_CUBE_MAP_NEGATIVE_Y)
        .colorTarget(3, colorTarget, PicoGL.TEXTURE_CUBE_MAP_POSITIVE_Y)
        .colorTarget(4, colorTarget, PicoGL.TEXTURE_CUBE_MAP_NEGATIVE_Z)
        .colorTarget(5, colorTarget, PicoGL.TEXTURE_CUBE_MAP_POSITIVE_Z)
        .depthTarget(depthTarget);

        // GEOMETRY
        var box = utils.createBox({dimensions: [1.0, 1.0, 1.0]})
        var positions = app.createVertexBuffer(PicoGL.FLOAT, 3, box.positions);
        var uv = app.createVertexBuffer(PicoGL.FLOAT, 2, box.uvs);
        var normals = app.createVertexBuffer(PicoGL.FLOAT, 3, box.normals);

        var boxArray = app.createVertexArray()
        .vertexAttributeBuffer(0, positions)
        .vertexAttributeBuffer(1, uv)
        .vertexAttributeBuffer(2, normals);

        // UNIFORMS
        var cubemapProjMatrix = mat4.create();
        mat4.perspective(cubemapProjMatrix, Math.PI / 2, 1, 0.1, 10.0);

        var cubemapViewMatrix = mat4.create();
        var cubemapEyePosition = vec3.fromValues(1.2, 0, 1.2);
        mat4.lookAt(cubemapViewMatrix, cubemapEyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0));

        var cubemapViewProjMatrix = mat4.create();
        mat4.multiply(cubemapViewProjMatrix, cubemapProjMatrix, cubemapViewMatrix);

        var projMatrix = mat4.create();
        mat4.perspective(projMatrix, Math.PI / 2, canvas.width / canvas.height, 0.1, 10.0);

        var viewMatrix = mat4.create();
        var eyePosition = vec3.fromValues(1.3, -1.3, 1.3);
        mat4.lookAt(viewMatrix, eyePosition, vec3.fromValues(0, 0, 0), vec3.fromValues(0, 1, 0));

        var viewProjMatrix = mat4.create();
        mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);

        var skyboxViewMatrix = mat4.create();
        skyboxViewMatrix.set(viewMatrix);
        skyboxViewMatrix[12] = 0;
        skyboxViewMatrix[13] = 0;
        skyboxViewMatrix[14] = 0;

        var skyboxViewProjMatrix = mat4.create();
        mat4.multiply(skyboxViewProjMatrix, projMatrix, skyboxViewMatrix);

        // UNIFORM BUFFER
        var cubemapSceneUniformBuffer = app.createUniformBuffer([
            PicoGL.FLOAT_MAT4,
            PicoGL.FLOAT_VEC4
        ])
        .set(0, cubemapViewProjMatrix)
        .set(1, cubemapEyePosition)
        .update();

        var sceneUniformBuffer = app.createUniformBuffer([
            PicoGL.FLOAT_MAT4,
            PicoGL.FLOAT_VEC4
        ])
        .set(0, viewProjMatrix)
        .set(1, eyePosition)
        .update();

        var skyboxSceneUniforms = app.createUniformBuffer([
            PicoGL.FLOAT_MAT4,
            PicoGL.FLOAT_VEC4
        ])
        .set(0, skyboxViewProjMatrix)
        .set(1, eyePosition)
        .update();

        var modelMatrix = mat4.create();
        var rotateXMatrix = mat4.create();
        var rotateYMatrix = mat4.create();

        window.onresize = function() {
            app.resize(window.innerWidth, window.innerHeight);

            mat4.perspective(projMatrix, Math.PI / 2, app.width / app.height, 0.1, 10.0);
            mat4.multiply(viewProjMatrix, projMatrix, viewMatrix);
            mat4.multiply(skyboxViewProjMatrix, projMatrix, skyboxViewMatrix);

            sceneUniformBuffer.set(0, viewProjMatrix).update();
            skyboxSceneUniforms.set(0, skyboxViewProjMatrix).update();
        };

        utils.loadImages([
            "img/webgl-logo.png",
            "img/sky-negx.png",
            "img/sky-posx.png",
            "img/sky-negy.png",
            "img/sky-posy.png",
            "img/sky-negz.png",
            "img/sky-posz.png"
        ], function(images) {
            var texture = app.createTexture2D(images[0], { flipY: true });

            var skyCubemap = app.createCubemap({
                negX: images[1],
                posX: images[2],
                negY: images[3],
                posY: images[4],
                negZ: images[5],
                posZ: images[6],
            });

            // PROGRAM
            var vsSource =  document.getElementById("vertex-cube").text.trim();
            var vShader = app.createShader(PicoGL.VERTEX_SHADER, vsSource);

            var cubemapFsSource =  document.getElementById("fragment-cubemap").text.trim();
            var cubeMapProgram = app.createProgram(vShader, cubemapFsSource);

            var fsSource =  document.getElementById("fragment-cube").text.trim();
            var program = app.createProgram(vShader, fsSource);

            vShader.delete();

            var skyboxVsSource =  document.getElementById("vertex-skybox").text.trim();
            var skyboxFsSource =  document.getElementById("fragment-skybox").text.trim();
            var skyboxProgram = app.createProgram(skyboxVsSource, skyboxFsSource);

            var cubemapDrawCall = app.createDrawCall(cubeMapProgram, boxArray)
            .texture("tex", texture)
            .uniformBlock("SceneUniforms", cubemapSceneUniformBuffer);

            var cubeDrawCall = app.createDrawCall(program, boxArray)
            .texture("renderCubemap", colorTarget)
            .texture("skyCubemap", skyCubemap)
            .uniformBlock("SceneUniforms", sceneUniformBuffer);

            var skyboxDrawcall = app.createDrawCall(skyboxProgram, boxArray)
            .texture("renderCubemap", colorTarget)
            .texture("skyCubemap", skyCubemap)
            .uniformBlock("SceneUniforms", skyboxSceneUniforms)

            var angleX = 0;
            var angleY = 0;

            function draw() {
                if (timer.ready()) {
                    utils.updateTimerElement(timer.cpuTime, timer.gpuTime);
                }

                timer.start();

                angleX += 0.01;
                angleY += 0.02;

                mat4.fromXRotation(rotateXMatrix, angleX);
                mat4.fromYRotation(rotateYMatrix, angleY);
                mat4.multiply(modelMatrix, rotateXMatrix, rotateYMatrix);

                cubemapDrawCall.uniform("uModel", modelMatrix);
                cubeDrawCall.uniform("uModel", modelMatrix);

                // DRAW SAME IMAGE TO ALL SIX FACES OF CUBEMAP
                app
                .drawFramebuffer(cubemapBuffer)
                .viewport(0, 0, CUBEMAP_DIM, CUBEMAP_DIM)
                .clear();
                cubemapDrawCall.draw();
                
                // RENDER TO SCREEN
                app.defaultDrawFramebuffer().defaultViewport();
                skyboxDrawcall.draw();
                cubeDrawCall.draw();

                timer.end(); 

                requestAnimationFrame(draw);
            }

            requestAnimationFrame(draw);
        }); 

    </script>
    <a href="https://github.com/tsherif/picogl.js" id="github-ribbon"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/365986a132ccd6a44c23a9169022c0b5c890c387/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f7265645f6161303030302e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"></a>
    <script src="../site/js/iframe.js"></script>
</body>
</html>
